package com.ruoyi.syf.handler.task.strategy;

import com.ruoyi.common.utils.CronUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MyCalendar;
import com.ruoyi.syf.common.constant.TaskType;
import com.ruoyi.syf.handler.task.TaskStrategy;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 隐患排查定时任务策略-自定义1（简单递增类型）
 *
 * @author yr
 * @date 2024-07-31
 */
@Service
public class IncrementalTaskStrategy implements TaskStrategy {
    @Override
    public String getTaskType() {
        return TaskType.INCREMENTAL;
    }

    @Override
    public String toCronExpression(int num, String timeUnit, Date startTime) throws IllegalAccessException {
        MyCalendar calendar = new MyCalendar(startTime);
        return CronUtil.toCronExpression(calendar,num,timeUnit,startTime);
    }

    @Override
    public Date getNextBeginTime(Date date, Date startTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return DateUtils.getNextDateByCycle(date, cycle, cycleUnit);
    }

    @Override
    public Date getLastBeginTime(Date startTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return DateUtils.getLastDateByCycle(startTime, cycle, cycleUnit);
    }

    @Override
    public Date getRecentBeginTime(Date startTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return getTimeByCycle(startTime, cycle, cycleUnit, System.currentTimeMillis());
    }

    private Date getTimeByCycle(Date startTime, Integer cycle, String cycleUnit, long time) throws IllegalAccessException {
        Date dateByCycle = DateUtils.getNextDateByCycle(startTime, cycle, cycleUnit);
        if (dateByCycle.getTime() <= time) {
            return getTimeByCycle(dateByCycle, cycle, cycleUnit, time);
        }
        return dateByCycle;
    }

}
